var net =require('net'),
    request = require('request'),
    App = require("../common/App.js"),
    UsableProxyPool = require("./UsableProxyPool.js")

/**
 * 保持连接的代理
 * @constructor
 */
module.exports = new KeepAlivePool();

function KeepAlivePool(){
    //单例模式
    if(typeof arguments.callee.instance === "object"){
        return arguments.callee.instance;
    }
    this.keepAliveList = {} ;
    this.timeoutSec = 1100;
    this.timeoutTimes = 3;
    this.sleepRetry = 1100;//等待重试时间

    arguments.callee.instance = this;
}

/**
 * 增加代理
 * @param proxy
 */
KeepAlivePool.prototype.add = function(proxy,times){
    var port = proxy.port;
    var host = proxy.host;
    var k = host+":"+port;

    var that = this;
    if(that.keepAliveList[k]!=undefined){
        return true;
    }
    if(isNaN(times)){
        times = 0;
    }
    if(times>this.timeoutTimes){
        if(times!= (this.timeoutTimes+2) ){//不是强制断开，需要通知服务器
            this.unusable(proxy);
        }
        delete this.keepAliveList[k];
        console.log("del");
        return true;
    }
    var isError = false;
    var isConnect = false;

    var retry = function(){
        if(!isError && !isConnect){
            isError = true;
            times++;
            console.log(k+"第"+times+"次重试");
            that.add(proxy,times);
        }
    }

    var client= new net.Socket();
    //连接到服务端
    client.connect(port,host,function(){

        isConnect = true;
        times = 0;
        that.keepAliveList[k] = {};
        that.keepAliveList[k].client = client;
        that.keepAliveList[k].proxy = proxy;

        UsableProxyPool.add(proxy);
        console.log(k+"连接成功");
    });
    client.setKeepAlive(true,30000);//设置30秒发一次心跳
    client.on('data',function(data){
        console.log('recv data:'+ data);
    });

    client.on('error',function(error){
        //console.log(times,"error");
        //console.log(that.sleepRetry);
        isConnect = false;
        setTimeout(retry,that.sleepRetry);
        //console.log('error:'+error);
    });
    client.on('close',function(flag){
        console.log(flag);
        if(flag=="disconnect"){
            times=that.timeoutTimes+1;
            console.log("强制断开");
            client.destroy();
        }else{
            isConnect = false;
            setTimeout(retry,that.sleepRetry);
        }
        //console.log('closed');
    });


    //连接超时后重试
    setTimeout(function(){
        //console.log(times,"timeout");
        retry();
    },that.timeoutSec);
}

/**
 * 与代理断开连接
 * @param proxy
 */
KeepAlivePool.prototype.del = function(proxy){
    var k = proxy.host+":"+proxy.port;
    if(this.keepAliveList[k]!=undefined && this.keepAliveList[k].client!=undefined){
        client = this.keepAliveList[k].client;
    }

    if(client!=undefined){
        try{
            //console.log(client);
            client.emit("close","disconnect");
        }catch (e){
            console.warn(e);
        }
    }
}

/**
 * 代理不可用，需要从代理池中删除
 * @param proxy
 */
KeepAlivePool.prototype.unusable = function(proxy){
    try{
        UsableProxyPool.del(proxy);
        var url = App.config.proxypool.del_url + "?proxy="+JSON.stringify(proxy);
        request.get(url);
    }catch (e){
        console.log(e);
    }
}


KeepAlivePool.prototype.all = function(){
    var list = [];
    for(var i in this.keepAliveList){
        list.push(this.keepAliveList[i].proxy);
    }
    return list;
}

